package com.sb.hot.ext.convert;

import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxiongkang
 */
@Configuration
public class CustomPropertyEditorConfiguration {
    @Bean
    public static TestPP testPP() {
        return new TestPP();
    }

    @Bean
    public static CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
        /**
         * 如果类型是User，则调用value解析器PointPropertEditor完成注入
         */
        Map<Class<?>, Class<? extends PropertyEditor>> customEditorMap = new HashMap<>(); customEditorMap.put(User.class, UserPropertEditor.class);
        customEditorConfigurer.setCustomEditors(customEditorMap); return customEditorConfigurer;
    }

    static class UserPropertEditor extends PropertyEditorSupport {
        /**
         * 接收value的注解值text
         *
         * @param text
         *
         * @throws IllegalArgumentException
         */
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            /**
             * 创建一个对象，以value注解内的值作为参数给这个对象
             */
            User user = new User(); user.setUsername(text.split("x")[0]);
            // user.setPassword(text.split("x")[1]);
            /**
             * 将这个对象注入到指定属性
             */
            setValue(user);
        }
    }
}
